###############################################################################
# SNOW.R
#
# Distributes simulations to different CPUs
#
# Last edited: 14 January 2015 by Roni 
###############################################################################

rm(list = ls(all = TRUE))

args <- commandArgs()

library(snowfall)
sfSetMaxCPUs(number=80)
load("input.list.Rdata")
socketHosts <- unlist(strsplit(args[6], ","))
socketHosts <- rep(substr(socketHosts, 1, nchar(socketHosts)-3),16)
print(socketHosts)

start <- eval(parse(text=args[7]))
end <- eval(parse(text=args[8]))

print(paste0("start=", start, ", end=", end))

 voters <- 1000          
## # Rule 0 = random, 1 = Hunter, 2 = Aggregator, 3 = Governator, 4=Sticker, 5=governator.largest
## # 6=governator.closest 7 = Satisficing Hunter, 8 = Reeser.Hunter, 9 = Reeser.Governator, 10 = Reeser.Gov.Largest
potential.rules <-  c(3,8,7,2,4) #rules which may appear in the simulation

folder <- "mc_newfor/evo/results/"


cpus <- length(socketHosts) #number of CPUs to use 


sfInit(type="SOCK", socketHosts=socketHosts, parallel=TRUE, cpus=cpus) #start cluster 
sfLibrary(nnet)               #load packages on slaves
sfLibrary(plyr)               #load packages on slaves
sfLibrary(pcaPP)              #for geometric median
sfLibrary(msm)                #for truncated normal
sfLibrary(compiler)                #for compiling of functions
sfLibrary(data.table)                #for compiling of functions
sfSource("speedy.engine.R")
sfSource("speedy.formater.ties.R")   #load functions on slaves
sfSource("speedy.sim.function.R")

## works like apply but sends each simulation to different CPUs
sfClusterApplyLB(input.list[start:end], 
                 wrapper.sim.function,
                 voters=voters,
                 folder=folder,
                 potential.rules=potential.rules) 
sfStop() # this stops the clusterprint("FINISHED")
print(Sys.time())
